package com.fm.common.wediget

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.blankj.utilcode.util.ImageUtils
import com.fm.common.R

/**
 *
 * @Author:         ly2
 * @CreateDate:     2020/12/22
 * @Description:
 *
 */
class ImageTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : AppCompatTextView(context, attrs) {
    private val mHeight: Int
    private val mWidth: Int
    private var mDrawable: Drawable?
    private val mLocation: Int

    companion object {
        const val LEFT = 1
        const val TOP = 2
        const val RIGHT = 3
        const val BOTTOM = 4
    }

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.ImageTextView)
        mWidth = a.getDimensionPixelSize(R.styleable.ImageTextView_drawable_width, 0)
        mHeight = a.getDimensionPixelSize(R.styleable.ImageTextView_drawable_height, 0)
        mDrawable = a.getDrawable(R.styleable.ImageTextView_drawable_src)
        mLocation = a.getInt(R.styleable.ImageTextView_drawable_location, LEFT)
        a.recycle()
        //绘制Drawable宽高,位置
        drawDrawable()
    }

    /**
     * 绘制Drawable宽高,位置
     */
    private fun drawDrawable() {
        if (mDrawable != null) {
            val bitmap = ImageUtils.drawable2Bitmap(mDrawable)
            val drawable: Drawable = if (mWidth != 0 && mHeight != 0) {
                BitmapDrawable(resources, Bitmap.createScaledBitmap(bitmap, mWidth, mHeight, true))
            } else {
                mDrawable!!
            }
            when (mLocation) {
                LEFT -> this.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
                TOP -> this.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null)
                RIGHT -> this.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
                BOTTOM -> this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable)
            }
        }
    }

    /**
     * 缩放图片
     *
     * @param bm        图片
     * @param newWidth  设置宽度
     * @param newHeight 设置高度
     * @return 返回调整后图片
     */
    private fun getBitmap(bm: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
        // 获得图片的宽高
        val width = bm.width
        val height = bm.height
        // 计算缩放比例
        val scaleWidth = newWidth.toFloat() / width
        val scaleHeight = newHeight.toFloat() / height
        // 取得想要缩放的matrix参数
        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleHeight)
        // 得到新的图片
        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true)
    }

    fun setDrawable(drawable: Drawable) {
        mDrawable = drawable
        drawDrawable()
    }
}